//
//  StudySettingsViewController.swift
//  SitPosition
//
//  Created by apple on 2019/1/1.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation
import UIKit
import Toast_Swift
import Cartography


/**
 * TTS声音类型
 */
enum TTSVoice : Int {
    case man = 0
    case woman = 1
    
    func name() -> String {
        switch self {
        case .man: return Strings.studySettingManVoice
        case .woman: return Strings.studySettingWomanVoice
        }
    }
}

/**
 * 学习设置页面
 */
class StudySettingsViewController : GKNavigationBarViewController {
    
    // 学习设置项
    private enum Setting {
        case positionAngle(angle: Float?)       // 范围：0~2
        case studyMaxDuration(duration: Int?)   // 单位：分钟
        case idleDuration(duration: Int?)       // 单位：分钟
        case triggerTime(time: Int?)            // 单位：秒
        case ttsVoice(voiceType: TTSVoice?)     // 暂时保留
        
        func ivName() -> (imageName: String, title: String, subtitle: String?) {
            switch self {
            case .positionAngle:
                return ("tool_angle", Strings.studySettingAngle, Strings.studySettingAngleDesc)
            case .studyMaxDuration:
                return ("tool_continuity", Strings.studySettingDuration, Strings.studySettingDurationDesc)
            case .idleDuration:
                return ("tool_phone", Strings.studySettingIdleDuration, Strings.studySettingIdleDurationDesc)
            case .ttsVoice:
                return ("tool_speak", Strings.studySettingVoice, Strings.studySettingVoiceDesc)
            case .triggerTime:
                return ("tool_time", Strings.studySettingTriggerTime, Strings.studySettingTriggerTimeDesc)
            }
        }
        
        var valueDisplayName: String? {
            switch self {
            case .positionAngle(let angle):
                return angle == nil ? nil:"\(angle!)°"
            case .studyMaxDuration(let duration):
                return duration == nil ? nil:"\(duration!)\(Strings.unitMinutes)"
            case .idleDuration(let duration):
                return duration == nil ? nil:"\(duration!)\(Strings.unitMinutes)"
            case .ttsVoice(let voiceType):
                return voiceType?.name()
            case .triggerTime(let time):
                return time == nil ? nil:"\(time!)\(Strings.unitSeconds)"
            }
        }
    }
    
    // 标题
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = Theme.Color.primaryDarkTextColor
        label.font = Theme.Font.boldFont(ofSize: 26)
        label.numberOfLines = 1
        label.lineBreakMode = .byTruncatingTail
        label.text = Strings.studySettings
        return label
    }()
    
    // 列表
    lazy var tableView: UITableView = {
        let table = UITableView(frame: CGRect.zero, style: UITableView.Style.plain)
        table.separatorColor = Theme.Color.primaryDarkSeperatorColor
        table.separatorInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
        table.dataSource = self
        table.delegate = self
        table.rowHeight = UITableView.automaticDimension
        table.estimatedRowHeight = 90
        table.register(SettingTableViewCell.self, forCellReuseIdentifier: SettingTableViewCell.reusedIdentifier)
        return table
    }()
    
    // 数据源
    private var settings: [Setting] = []
    
    
    // MARK: - Object lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 导航栏
        gk_navBackgroundColor = UIColor.clear
        gk_navLeftBarButtonItem = UIBarButtonItem(imageName: "ic_nav_back_black", target: self, action: #selector(_backButtonTapped))
        
        // 子视图
        view.addSubviews([
            titleLabel,
            tableView
        ])
        _setupContraints()
        view.backgroundColor = UIColor.white
        
        // 当前配置
        _refreshSettingsDataSource()
        
        // 加载用户配置
        view.makeToastActivity(.center)
        UserConfigs.refreshCurrentUserConfigs { [weak self] error in
            defer {
                self?.view.hideToastActivity()
            }
            self?._refreshSettingsDataSource()
            self?.tableView.reloadData()
        }
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return UIStatusBarStyle.default
    }
}

// MARK: - UITableViewDataSource/UITableViewDelegate

extension StudySettingsViewController : UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return settings.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SettingTableViewCell.reusedIdentifier, for: indexPath) as! SettingTableViewCell
        
        let data: Setting = settings[indexPath.row]
        let (imageName, title, subtitle) = data.ivName()
        
        cell.iconIV.image = UIImage(named: imageName)
        cell.titleLabel.text = title
        cell.subtitleLabel.text = subtitle
        cell.valueLabel.text = data.valueDisplayName
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        // 响应点击逻辑
        let data: Setting = settings[indexPath.row]
        switch data {
        case let .positionAngle(angle):
            _pickPositionAngle(angle)
        case let .triggerTime(time):
            _pickTriggerTime(time)
        case let .studyMaxDuration(duration):
            _pickStudyMaxDuration(duration)
        case let .idleDuration(duration):
            _pickIdleDuration(duration)
        default: break
        }
    }
}

// MARK: - Private Methods

extension StudySettingsViewController {
    
    // 设置视图约束
    func _setupContraints() {
        // titleLabel
        constrain(titleLabel, gk_navigationBar, view) { v, sibling, parent in
            v.top == sibling.bottom + 19
            v.left == parent.left + 16
            v.right == parent.right - 16
            v.height == 25
        }
        
        // tableView
        constrain(tableView, titleLabel, view) { v, sibling, parent in
            v.top == sibling.bottom
            v.left == parent.left
            v.right == parent.right
            v.bottom == parent.bottom
        }
    }
    
    // 选坐姿角度
    func _pickPositionAngle(_ angle: Float?) {
        let values: [Float] = (10..<14).map {
            Float($0) / 10.0
        }
        let storedValue: Float = UserConfigs.current?.angleValue ?? UserConfigs.defaultAngle
        let selectedRow: Int = values.firstIndex { $0 == storedValue } ?? values.count-1
        
        let picker = ValuePickerControlelr<Float>()
        picker.items = values.map { v in
            let s = String(format: "%.1f", v)
            return (title: "\(s)º", value: v)
        }
        picker.selectedRow = selectedRow
        picker.onGotValue = { [weak self] _, value in
            if let value_ = value {
                UserConfigs.current?.angleValue = value_
                self?._commitChanges()
                self?.tableView.reloadData()
            }
            self?.dismiss(animated: true, completion: nil)
        }
        picker.onAdvanceSetting = { [weak self] in
            let vc = StudyAngleAdvSettingsViewController()
            self?.dismiss(animated: false, completion: nil)
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        picker.modalPresentationStyle = .overCurrentContext
        picker.modalTransitionStyle = .crossDissolve
        present(picker, animated: true, completion: nil)
    }
    
    // 报警触发时间
    func _pickTriggerTime(_ time: Int?) {
        let values: [Int] = (3..<16).map { $0 }
        let storedValue: Int = (UserConfigs.current?.alarmTime ?? UserConfigs.defaultAlarmTime)
        let selectedRow: Int = values.firstIndex { $0 == storedValue } ?? 3
        
        let picker = ValuePickerControlelr<Int>()
        picker.items = values.map { v in
            return (title: "\(v)\(Strings.unitSeconds)", value: v)
        }
        picker.selectedRow = selectedRow
        picker.onGotValue = { [weak self] _, value in
            if let value_ = value {
                UserConfigs.current?.alarmTime = value_
                self?._commitChanges()
                self?.tableView.reloadData()
            }
            self?.dismiss(animated: true, completion: nil)
        }
        picker.modalPresentationStyle = .overCurrentContext
        picker.modalTransitionStyle = .crossDissolve
        present(picker, animated: true, completion: nil)
    }
    
    // 连续学习时长
    func _pickStudyMaxDuration(_ duration: Int?) {
        let inputr = ValueInputController()
        inputr.configuration = { titleLable, tf, unitLabel in
            let studyTime = (UserConfigs.current?.studyTime ?? UserConfigs.defaultStudyTime)/60
            tf.text = String(studyTime)
            tf.keyboardType = UIKeyboardType.numberPad
            unitLabel.text = Strings.unitMinutes
            titleLable.text = Strings.studySettingDuration.replacingOccurrences(of: Strings.settings, with: "")
        }
        inputr.onGotValue = { [weak self] value in
            if let value_ = value, let intValue = Int(value_) {
                UserConfigs.current?.studyTime = intValue*60
                self?._commitChanges()
                self?.tableView.reloadData()
            }
            self?.dismiss(animated: true, completion: nil)
        }
        
        inputr.modalPresentationStyle = .overCurrentContext
        inputr.modalTransitionStyle = .crossDissolve
        present(inputr, animated: true, completion: nil)
    }
    
    // 自动黑屏时间
    func _pickIdleDuration(_ duration: Int?) {
        // 转换以秒为单位的时间
        func formatTimeInSecond(_ seconds: Int) -> String {
            if seconds < 60 {
                return "\(seconds)\(Strings.unitSeconds)"
            } else if seconds < 60*60 {
                return "\(seconds/60)\(Strings.unitMinutes)"
            } else {
                return "\(seconds/3600)\(Strings.unitHours)"
            }
        }
        
        let values: [Int] = [   // 秒
            15, 30, 60, 2*60, 5*60, 10*60, 30*60, 60*60
        ]
        let storedValue: Int = (UserConfigs.current?.blackScreenTime ?? UserConfigs.defaultBlackScreenTime)
        let selectedRow: Int = values.firstIndex { $0 == storedValue } ?? 3
        
        let picker = ValuePickerControlelr<Int>()
        picker.items = values.map { v in
            return (title: formatTimeInSecond(v), value: v)
        }
        picker.selectedRow = selectedRow
        picker.onGotValue = { [weak self] _, value in
            if let value_ = value {
                UserConfigs.current?.blackScreenTime = value_
                self?._commitChanges()
                self?.tableView.reloadData()
            }
            self?.dismiss(animated: true, completion: nil)
        }
        picker.modalPresentationStyle = .overCurrentContext
        picker.modalTransitionStyle = .crossDissolve
        present(picker, animated: true, completion: nil)
    }
    
    private func _commitChanges() {
        view.makeToastActivity(ToastPosition.center)
        UserConfigs.current?.save(true) { [weak self] error in
            self?.view.hideToastActivity()
            if let error_ = error {
                self?.view.makeToast(String(describing: error_))
            }
        }
        _refreshSettingsDataSource()
    }
    
    // 刷新数据源
    func _refreshSettingsDataSource() {
        settings = [
            Setting.positionAngle(angle: UserConfigs.current?.angleValue ?? UserConfigs.defaultAngle),
            Setting.triggerTime(time: UserConfigs.current?.alarmTime ?? UserConfigs.defaultAlarmTime),
            Setting.studyMaxDuration(duration: (UserConfigs.current?.studyTime ?? UserConfigs.defaultStudyTime)/60),
            Setting.idleDuration(duration: (UserConfigs.current?.blackScreenTime ?? UserConfigs.defaultBlackScreenTime)/60)
            // Setting.ttsVoice(voiceType: TTSVoice.woman)
        ]
    }
    
    // 返回按钮点击事件
    @objc func _backButtonTapped() {
        if presentingViewController != nil {
            dismiss(animated: true, completion: nil)
        } else {
            navigationController?.popViewController(animated: true)
        }
    }
}
